package context;

import com.alibaba.fastjson.JSONArray;
import com.github.houbb.heaven.util.util.CollectionUtil;
import core.impl.DefaultBeanFactory;
import core.impl.DefaultListableBeanFactory;
import model.impl.DefaultBeanDefinition;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import util.util.FileUtil;

import java.io.InputStream;
import java.util.List;


/**
 * @author Max
 * <br>
 * date 2019/12/18 16:50
 * <p>
 *     json 的应用上下文
 * </p>
 * @version 0.2
 */

public class JsonApplicationContext extends DefaultListableBeanFactory {

    private static final Logger logger = LogManager.getLogger(JsonApplicationContext.class);


    /**
     * json 文件
     * @since 0.1
     */
    private final String fileName;


    public JsonApplicationContext(String fileName){
        this.fileName = fileName;

        logger.info("初始化Json应用上下文");

        this.init();
    }

    /**
     * 初始化相关配置文件
     */
    private void init() {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
        String content = FileUtil.getFileContent(is);

        List<DefaultBeanDefinition> defaultBeanDefinitions = JSONArray.parseArray(content, DefaultBeanDefinition.class);
        if(CollectionUtil.isNotEmpty(defaultBeanDefinitions)){
            for(DefaultBeanDefinition beanDefinition : defaultBeanDefinitions) {
                super.registerBeanDefinition(beanDefinition.getName(),beanDefinition);
            }
        }

    }
}